<?php
//上传文件

namespace app\shop\controller;
use think\Request;
use think\Exception;

class File extends \ShopController
{
    /**
     * 上传图片
     * @return \think\response\Json
     */
    public function uploadImage()

    {
        // 获取表单上传文件
        $file = request()->file('image');

        /* @var $file \Think\File */
        $info = $file->validate([
            'size' => 1024 * 1024 * 2,
            'ext' => 'jpg,jpeg,png',
        ])->move(GOODS_IMAGE_SAVE_PATH);

        if ($info) {
            // 成功上传后 获取上传信息
            // 输出 jpg
//            echo $info->getExtension();
            // 输出 42a79759f284b767dfcb2a0197904287.jpg
//            echo $info->getFilename();

//            $images[] = $info->getSaveName();
            $this->successTerminate(GOODS_IMAGE_URL . $info->getSaveName());
        } else {
            // 上传失败获取错误信息
            $this->serverErrorTerminate($file->getError());
        }
    }

    /**
     * 上传图片
     * @return \think\response\Json
     */
    public function uploadAccessory()

    {
        // 获取表单上传文件
        $file = request()->file('accessory');
       $file=
        /* @var $file \Think\File */
        $info = $file->validate([
            'size' => 1024 * 1024 * 2,
            'ext' => 'pdf,word,excel,txt,jpg,png,bmp,gif,rar,zip',
        ])->move(GOODS_ACCESSORY_SAVE_PATH);

        if ($info) {
            // 成功上传后 获取上传信息
            // 输出 jpg
//            echo $info->getExtension();
            // 输出 42a79759f284b767dfcb2a0197904287.jpg
//            echo $info->getFilename();

//            $images[] = $info->getSaveName();
           $d =  [
                'url'=>GOODS_ACCESSORY_URL . $info->getSaveName(),
                'name'=>$file->getInfo('name'),
                '_t'=>GOODS_ACCESSORY_URL . $info->getSaveName().'|'.$file->getInfo('name'),
            ];
            $this->successTerminate($d);
        } else {
            // 上传失败获取错误信息
            $this->serverErrorTerminate($file->getError());
        }
    }

    public function upload(Request $request){
        $action = $request->param('action');
        switch($action){
            case 'config':
                $result = file_get_contents(ROOT_PATH.'public/static/ueditor/config.json');
                break;
            case 'uploadimage':
                $file = request()->file('upfile');

                $info = $file->validate([
                    'size' => 1024 * 1024 * 2,
                    'ext' => 'jpg,jpeg,png',
                ])->move(GOODS_IMAGE_SAVE_PATH);

                if ($info) {
                    $res['state'] = 'SUCCESS';
                    $res['url'] = GOODS_IMAGE_URL . $info->getSaveName();
                    $result = json_encode($res);
                }
            default:
                break;
        }
        return $result;
    }

    public function download(Request $request){
        try{
            $url = $request->post('url');
            if(!empty($url)){
                $base64_file = '';
                $accessory_info = $this->remote_filesize($url,3);
                $file_data = fread(fopen($url, 'r'), strlen(file_get_contents($url)));
                $base64_file = 'data:' . $accessory_info['mime'] . ';base64,' . chunk_split(base64_encode($file_data));

                $this->successTerminate($base64_file);
            }
        }catch(Exception $e){
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    function remote_filesize($strUrl,$intType=1,$arrOptional=array()){
        $arrRet=array(
            "length"=>0,                    //大小，字节为单位
            "mime"=>"",                     //mime类型
            "filename"=>"",                 //文件名
            "status"=>0                     //状态码
        );
        switch($intType){
            case 1:
                //利用get_headers函数
                if(($arrTmp=get_headers($strUrl,true))){
                    $arrRet=array("length"=>$arrTmp['Content-Length'],"mime"=>$arrTmp['Content-Type']);
                    if(preg_match('/filename=\"(.*)\"/si',$arrTmp['Content-Disposition'],$arr)){
                        $arrRet["filename"]=$arr[1];
                    }
                    if(preg_match('/\s(\d+)\s/',$arrTmp[0],$arr)){
                        $arrRet["status"]=$arr[1];
                    }
                }
                break;
            case 2:
                //利用fsocket
                if(($arrUrl=parse_url($strUrl))){
                    if($fp=@fsockopen($arrUrl['host'],empty($arrUrl['port'])?80:$arrUrl['port'],$error)){
                        @fputs($fp,"GET ".(empty($arrUrl['path'])?'/':$arrUrl['path'])." HTTP/1.1\r\n");
                        @fputs($fp,"Host: $arrUrl[host]\r\n");
                        @fputs($fp,"Connection: Close\r\n\r\n");
                        while(!feof($fp)){
                            $tmp=fgets($fp);
                            if(trim($tmp)==''){
                                //此行代码只读到头信息即可
                                break;
                            }else{
                                (preg_match('/(HTTP.*)(\s\d{3}\s)/',$tmp,$arr))&&$arrRet['status']=trim($arr[2]);
                                (preg_match('/Content-Length:(.*)/si',$tmp,$arr))&&$arrRet['length']=trim($arr[1]);
                                (preg_match('/Content-Type:(.*)/si',$tmp,$arr))&&$arrRet['mime']=trim($arr[1]);
                                (preg_match('/filename=\"(.*)\"/si',$tmp,$arr))&&$arrRet['filename']=trim($arr[1]);
                            }
                        }
                        @fclose($fp);
                    }
                }
                break;
            case 3:
                //利用curl
                if(($ch=curl_init($strUrl))){
                    curl_setopt($ch,CURLOPT_HEADER,1);
                    curl_setopt($ch,CURLOPT_NOBODY,1);
                    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
                    if(isset($arrOptional['user'])&&isset($arrOptional['password'])){
                        $headers=array('Authorization: Basic '.base64_encode($arrOptional['user'].':'.$arrOptional['password']));
                        curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
                    }
                    $tmp=curl_exec($ch);
                    curl_close($ch);
                    (preg_match('/Content-Length:\s([0-9].+?)\s/',$tmp,$arr))&&$arrRet['length']=trim($arr[1]);
                    (preg_match('/Content-Type:\s(.*)\s/',$tmp,$arr))&&$arrRet['mime']=trim($arr[1]);
                    (preg_match('/filename=\"(.*)\"/i',$tmp,$arr))&&$arrRet['filename']=trim($arr[1]);
                    (preg_match('/(HTTP.*)(\s\d{3}\s)/',$tmp,$arr))&&$arrRet['status']=trim($arr[2]);
                }
                break;
            case 4:
                //本地处理
                if(file_exists($strUrl)) {
                    $arrRet=array(
                        "length"=>filesize($strUrl),
                        "mime" =>mime_content_type($strUrl),
                        "filename"=>basename($strUrl),
                        "status"=>200
                    );
                }else{
                    $arrRet=array(
                        "length"=>0,
                        "mime" =>'',
                        "filename"=>basename($strUrl),
                        "status"=>404
                    );
                }
                break;
        }
        if(isset($arrOptional['getimagesize'])&&$arrRet['status']=='200'){
            if(($arrTmp=@getimagesize($strUrl))){
                $arrRet['width']=$arrTmp[0];
                $arrRet['height']=$arrTmp[1];
                $arrRet['type']=$arrTmp[2];
                $arrRet['tag']=$arrTmp[3];
                $arrRet['bits']=$arrTmp['bits'];
                $arrRet['channels']=$arrTmp['channels'];
                !isset($arrRet['mime'])&&$arrRet['mime']=$arrTmp['mime'];
            }
        }
        return $arrRet;
    }

}